package one;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import one.pojo.MyValue;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class SimpleUseObjectMapper {
    public static void main(String[] args) throws IOException {
        //从文件中读取
        readValueFromFile();
//        从url中读取
        readValueFromUrl();
//        读取字符串中读取
        readValueFromString();


//        将对象的json写入文件
        writeObjectToFile();
//        将对象的json写入到字符串
        writeObjectToString();
//        将对象的json写入byte[]
        writeObjectToByteArray();
    }

    private static void writeObjectToString() throws IOException {
        MyValue wpp = new MyValue("wpp", 13);
        new ObjectMapper().writeValue(new File("wpp.json"), wpp);
    }

    private static void writeObjectToByteArray() throws JsonProcessingException {
        MyValue wpp = new MyValue("wpp", 14);
        String wppJson = new ObjectMapper().writeValueAsString(wpp);
        System.out.println(wppJson);
    }

    private static void writeObjectToFile() throws JsonProcessingException {
        MyValue wpp = new MyValue("wpp", 14);
        byte[] bytes = new ObjectMapper().writeValueAsBytes(wpp);
        System.out.println(bytes.length);
    }

    private static void readValueFromString() throws JsonProcessingException {
        String dataJsonString = "{\"name\": \"wpp\",\"age\": 20}";
        ObjectMapper mapper = new ObjectMapper();
        MyValue value = mapper.readValue(dataJsonString, MyValue.class);
        System.out.println(value);
    }

    private static void readValueFromUrl() throws IOException {
        URL dataJsonURL = SimpleUseObjectMapper.class.getClassLoader().getResource("one/data.json");
        ObjectMapper mapper = new ObjectMapper();
        MyValue value = mapper.readValue(dataJsonURL, MyValue.class);
        System.out.println(value);
    }

    private static void readValueFromFile() throws IOException {
        String dataJsonFile = SimpleUseObjectMapper.class.getClassLoader().getResource("one/data.json").getFile();

        ObjectMapper mapper = new ObjectMapper();
        MyValue value = mapper.readValue(new File(dataJsonFile), MyValue.class);
        System.out.println(value);

    }
}
